package com.github.defense.plugin.gray.decision.predicate;

import com.github.defense.plugin.gray.instance.GrayInstance;
import com.github.defense.plugin.gray.request.GrayRequest;
import com.google.common.collect.Lists;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author: lettger
 * @Date: 2021/6/22 12:47 下午
 */
public class DefaultPolicyPredicate implements PolicyPredicate {

    @Override
    public List<GrayInstance> test(Collection<PolicyDefinition> definitions, GrayRequest request) {
        if (CollectionUtils.isEmpty(definitions) || Objects.isNull(request)) {
            return Lists.newArrayList();
        }
        return definitions
                .stream()
                .filter(definition -> definition.getGrayDecision().test(request))
                .map(res -> res.getInstance())
                .collect(Collectors.toList());
    }
}
